<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="仓库" prop="storeId">
        <el-input
          v-model="queryParams.storeId"
          placeholder="请输入仓库"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="原料数量" prop="materialCount">
        <el-input
          v-model="queryParams.materialCount"
          placeholder="请输入原料数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="原料价格" prop="materialPrice">
        <el-input
          v-model="queryParams.materialPrice"
          placeholder="请输入原料价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="采购人" prop="staffId">
        <el-input
          v-model="queryParams.staffId"
          placeholder="请输入采购人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sales:material:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sales:material:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sales:material:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sales:material:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="仓库" align="center" prop="storeId" >
        <template slot-scope="scope">
          <span>{{ getStoreName(scope.row.storeId) }}</span> 
        </template>
      </el-table-column>
      <el-table-column label="原料" align="center" prop="stockId" >
        <template slot-scope="scope">
          <span>{{ getStockName(scope.row.stockId) }}</span> 
        </template>
      </el-table-column>
      <el-table-column label="原料数量" align="center" prop="materialCount" />
      <el-table-column label="原料价格(元)" align="center" prop="materialPrice" />
      <el-table-column label="采购人" align="center" prop="staffId" >
        <template slot-scope="scope">
          <span>{{ getStaffName(scope.row.staffId) }}</span> 
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sales:material:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sales:material:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改原料仓库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 若设置为 true，则表单内组件上的 disabled 属性不再生效 -->
        <el-form-item label="仓库" prop="storeId" :disabled="isEdit">
          <!-- <el-input v-model="form.storeId" placeholder="请输入仓库id" /> -->
          <el-select v-model="form.storeId" placeholder="请选择仓库" :disabled="isEdit">
            <el-option
              v-for="item in storeOptions"
              :key="item.storeId"
              :label="item.storeName"
              :value="item.storeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="原料" prop="stockId" :disabled="isEdit">
          <treeselect
                v-model="form.stockId"
                :options="stockOptions"
                :show-count="true"
                :disable-branch-nodes="true"
                placeholder="请选择原料"
                :disabled="isEdit"
              />
        </el-form-item>
        <el-form-item label="原料数量" prop="materialCount" :disabled="isEdit">
          <el-input v-model="form.materialCount" placeholder="请输入原料数量" type="number" :disabled="isEdit"/>
        </el-form-item>
        <el-form-item label="原料价格" prop="materialPrice" >
          <el-input v-model="form.materialPrice" placeholder="请输入原料价格" type="number"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial, storeListSelect } from "@/api/sales/material";
import { stockTreeSelect } from "@/api/sales/product";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Material",
  components: { Treeselect },
  data() {
    var validateMaterialCount = (rule, value, callback) => {  
      // 正则表达式，匹配正整数  
      const regex = /^\d+$/;
      if (!regex.test(value)) {  
        callback(new Error('请输入有效的正整数原料数量'));  
      } else if (value <= 0) {  
        callback(new Error('原料数量必须为正整数'));  
      } else {  
        callback();  
      } 
    };  
    var validateMaterialPrice = (rule, value, callback) => {  
      // 正则表达式，匹配正整数  
      const regex = /^\d+$/;
      if (!regex.test(value)) {  
        callback(new Error('请输入有效的正整数原料价格'));  
      } else if (value <= 0) {  
        callback(new Error('原料价格必须为正整数'));  
      } else {  
        callback();  
      } 
    };  
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 原料仓库表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeId: null,
        stockId: null,
        materialCount: null,
        materialPrice: null,
        staffId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        storeId: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
        stockId: [
          { required: true, message: "原料不能为空", trigger: "change" }
        ],
        materialCount: [
          { required: true, validator: validateMaterialCount, trigger: "blur" }
        ],
        materialPrice: [
          { required: true, validator: validateMaterialPrice, trigger: "blur" }
        ],
      },
      //仓库选项
      storeOptions: undefined,
      // 原料品类树选项
      stockOptions: undefined,
      // 原料品类名称
      stockName: undefined,
      // 添加还是修改
      isEdit: false,
    };
  },
  created() {
    this.getList();
    this.getStoreList();
    this.getStockTree();
  },
  methods: {
    getStaffName(staffId){
      // 遍历 materialList 数组以找到匹配的 staffId  
      const foundItem = this.materialList.find(item => item.staffId === staffId);  
      // 如果找到了匹配的项，返回其 staffName，否则返回空字符串或未定义  
      return foundItem ? foundItem.staffName : ''; 
    },
    getStockName(stockId){
      // 遍历 materialList 数组以找到匹配的 stockId  
      const foundItem = this.materialList.find(item => item.stockId === stockId);  
      // 如果找到了匹配的项，返回其 stockName，否则返回空字符串或未定义  
      return foundItem ? foundItem.stockName : ''; 
    },
    getStoreName(storeId){
      // 遍历 materialList 数组以找到匹配的 storeId  
      const foundItem = this.materialList.find(item => item.storeId === storeId);  
      // 如果找到了匹配的项，返回其 storeName，否则返回空字符串或未定义  
      return foundItem ? foundItem.storeName : ''; 
    },
    /** 查询原料品类下拉树结构 */
    getStockTree() {
      stockTreeSelect().then((response) => {
        this.stockOptions = response.data;
      });
    },
    // 查询仓库列表
    getStoreList(){
      storeListSelect().then((response) => {
        this.storeOptions = response.data;
      })
    },
    /** 查询原料仓库列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        materialId: null,
        storeId: null,
        stockId: null,
        materialCount: null,
        materialPrice: null,
        staffId: null,
        status: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        del: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.stockId = null;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.materialId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加原料仓库入库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const materialId = row.materialId || this.ids
      getMaterial(materialId).then(response => {
        this.form = response.data;
        this.open = true;
        this.isEdit = true;
        this.title = "修改原料仓库入库";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.materialId != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const materialIds = row.materialId || this.ids;
      this.$modal.confirm('是否确认删除原料仓库入库编号为"' + materialIds + '"的数据项？').then(function() {
        return delMaterial(materialIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sales/material/export', {
        ...this.queryParams
      }, `material_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
